﻿using Microsoft.AspNetCore.Mvc;
using MultiAgentsServer.Scripts.Hubs;
using MultiAgentsShared;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace MultiAgentsServer.Scripts.Services;

[Route("webhook")]
[ApiController]
public class WebhookService(IEventBus eventBus) : ControllerBase
{
    private readonly IEventBus _eventBus = eventBus;

    [HttpPost("trigger")]
    public async Task<IActionResult> Receive()
    {
        using StreamReader reader = new(Request.Body);
        string requestBody = await reader.ReadToEndAsync();

        try
        {
            GitLabMergeRequestEvent? mergeRequestEvent = JsonSerializer.Deserialize<GitLabMergeRequestEvent>(requestBody);

            if (mergeRequestEvent?.Project == null || mergeRequestEvent.ObjectAttributes == null)
            {
                return BadRequest("Missing essential merge request data");
            }

            Dictionary<string, string> mergeRequestInfo = new()
            {
                ["projectId"] = mergeRequestEvent.Project.Id.ToString(),
                ["mergeRequestId"] = mergeRequestEvent.ObjectAttributes.Iid.ToString(),
                ["repositoryUri"] = mergeRequestEvent.Project.GitHttpUrl ?? "",
                ["sourceBranch"] = mergeRequestEvent.ObjectAttributes.SourceBranch ?? "",
                ["targetBranch"] = mergeRequestEvent.ObjectAttributes.TargetBranch ?? "",
                ["title"] = mergeRequestEvent.ObjectAttributes.Title ?? "",
                ["description"] = mergeRequestEvent.ObjectAttributes.Description ?? ""
            };

            _eventBus.Publish(new RecievePullRequestCommand(mergeRequestInfo));

            return Ok();
        }
        catch (JsonException)
        {
            return BadRequest("Unable to parse JSON data");
        }
        catch (Exception)
        {
            return StatusCode(StatusCodes.Status500InternalServerError, "Internal server error");
        }
    }
}

public class GitLabMergeRequestEvent
{
    [JsonPropertyName("object_attributes")]
    public GitlabObjectAttributes? ObjectAttributes { get; set; }

    [JsonPropertyName("project")]
    public GitlabRepo? Project { get; set; }
}

public class GitlabObjectAttributes
{
    [JsonPropertyName("iid")]
    public int Iid { get; set; }

    [JsonPropertyName("source_branch")]
    public string? SourceBranch { get; set; }

    [JsonPropertyName("target_branch")]
    public string? TargetBranch { get; set; }

    [JsonPropertyName("title")]
    public string? Title { get; set; }

    [JsonPropertyName("description")]
    public string? Description { get; set; }
}

public class GitlabRepo
{
    [JsonPropertyName("id")]
    public int Id { get; set; }

    [JsonPropertyName("name")]
    public string? Name { get; set; }

    [JsonPropertyName("git_http_url")]
    public string? GitHttpUrl { get; set; }
}